package com.stone.mythread.juc;

import java.util.Random;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;

/**
 * 抢车位，6辆车，3个停车位
 */
public class ThreadSemaphore {

    public static void main(String[] args) {
        // 创建 Semaphore , 设置许可数量
        Semaphore semaphore = new Semaphore(3);

        // 模拟 6 量汽车
        for (int i = 1; i <= 6; i++) {
            new Thread(() -> {
                // 抢占车位
                try {
                    semaphore.acquire();
                    System.err.println(Thread.currentThread().getName() + " 抢到了车位。");
                    // 设置随机停车时间
                    TimeUnit.SECONDS.sleep(new Random().nextInt(5));
                    System.err.println(Thread.currentThread().getName() + " 离开了车位。");
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } finally {
                    // 释放
                    semaphore.release();
                }
            }, String.valueOf(i)).start();
        }
    }
}
